/*
* tls_error.cpp
*
*  Created on: Aug 22, 2020
*      Author: gyd
*/
#include <string.h>
#include <stdio.h>
#include "tls_error.h"

#define ERROR_MSG_LEN 512

static thread_local char tls_errmsg[ERROR_MSG_LEN + 1] = {'\0'};
static thread_local char tls_outmsg[ERROR_MSG_LEN + 1] = {'\0'};
void gdface::tls_set_errmsg(const char* file,int line,const char*msg){
	if(msg){
		if(file){
			// 只取文件名不含路径
			const char *base_name = strrchr(file,'/');
			if(!base_name){
				base_name = file;
			}
			snprintf(tls_errmsg,ERROR_MSG_LEN,"%s:%d %s",base_name,line,msg);
		}else{
			strncpy(tls_errmsg,msg,ERROR_MSG_LEN);
		}
		tls_errmsg[ERROR_MSG_LEN] = '\0';
	}else
		tls_errmsg[0] = '\0';
}

const char * gdface::tls_strerr () {
	if(strlen(tls_errmsg)){
		strncpy(tls_outmsg,tls_errmsg,ERROR_MSG_LEN);
		tls_errmsg[0] = '\0';
	}else if(errno){
		// 返回系统错误信息
		strncpy(tls_outmsg,strerror(errno),ERROR_MSG_LEN);
	}
	tls_outmsg[ERROR_MSG_LEN] = '\0';
	return tls_outmsg;
}
const char * gdface::tls_strerr_or_default(const char * default_msg) {
	const char* msg = tls_strerr();
	if (strlen(msg)) {
		return msg;
	}
	return default_msg;
}

void gdface::tls_perr(){
	fputs(tls_strerr(),stderr);
}
